package svc

import (
	"database/sql"

	"mall/common/modelx"
	"mall/service/order/repository"
	"mall/service/order/rpc/internal/config"
	"mall/service/product/rpc/productclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config     config.Config

	DB               *sql.DB
	Order            repository.OrderRepository
	AfterSaleRequest repository.AfterSaleRequestRepository
	OrderReaction    repository.OrderReactionRepository
	Cart             repository.CartItemRepository
	CompanyAddress   repository.CompanyAddressRepository

	ProductRpc productclient.Product
	UserRpc    userclient.User
}

func NewServiceContext(c config.Config) *ServiceContext {
	db, err := modelx.NewMysqlConn(c.Mysql.DataSource)
	if err != nil {
		logx.Must(err)
	}

	return &ServiceContext{
		Config:     c,

		DB:               db,
		Order:            repository.NewOrderRepository(db, c.CacheRedis),
		AfterSaleRequest: repository.NewAfterSaleRequestRepository(db, c.CacheRedis),
		OrderReaction:    repository.NewOrderReactionRepository(db),
		Cart:             repository.NewCartItemRepository(db),
		CompanyAddress:   repository.NewCompanyAddressRepository(db, c.CacheRedis),

		ProductRpc: productclient.NewProduct(zrpc.MustNewClient(c.ProductRpc)),
		UserRpc:    userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),
	}
}
